package com.longxiao.validator.handler;

import com.longxiao.validator.ValidException;
import com.longxiao.validator.ValidResult;
import com.longxiao.validator.handler.cond.CommCondition;
import com.longxiao.validator.handler.cond.NumberCondition;

/**
 * Created by houhongwei on 2017/5/16.
 */
public class ValidNumberHandler extends CommHandler implements ValidHandler {

    @Override
    public ValidResult validOther(Object value, CommCondition cond) throws ValidException {
        NumberCondition numCond = null;
        if (cond instanceof NumberCondition) {
            numCond = (NumberCondition) cond;
        } else {
            return ValidResult.createSucc();
        }
        try {
            Double d = getDouble(value, numCond);
            min(d, numCond);
            max(d, numCond);
            ref(d, numCond);
        } catch (ValidException e) {
            return ValidResult.createFail(e.getMsg());
        }
        return ValidResult.createSucc();
    }

    private Double getDouble(Object value, NumberCondition numCond) throws ValidException {
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        } else {
            throw new ValidException(getErr(numCond));
        }
    }

    private void min(Double value, NumberCondition numCond) throws ValidException {
        if (numCond.getMin() != null && value < numCond.getMin()) {
            throw new ValidException(getErr(numCond));
        }
    }

    private void max(Double value, NumberCondition numCond) throws ValidException {
        if (numCond.getMax() != null && value > numCond.getMax()) {
            throw new ValidException(getErr(numCond));
        }
    }

    private void ref(Double value, NumberCondition numCond) throws ValidException {
        double[] ref = numCond.getRef();
        if (ref != null) {
            boolean bool = Boolean.FALSE;
            for (double d : ref) {
                if (d == value.doubleValue()) {
                    bool = Boolean.TRUE;
                    break;
                }
            }
            if (bool == Boolean.FALSE) {
                throw new ValidException(getErr(numCond));
            }
        }
    }
}
